<template>
  <div class="app-container">
     <el-row :gutter="20">
        <el-col :span="4" :xs="24">
           <div class="head-container">
              <el-input v-model="cateName" placeholder="请输入产品分类" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="cateOptions" :props="cateOptions" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
            </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="产品名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入产品名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="产品编码" prop="code">
              <el-input
                v-model="queryParams.code"
                placeholder="请输入产品编码"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                   <el-option
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
              plain
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['crm:product:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
              plain
                type="success"
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['crm:product:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
              plain
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['crm:product:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
              plain
                type="warning"
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['crm:product:import']"
              >导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
              plain
                type="warning"
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['crm:product:export']"
              >导出</el-button>
            </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="productId" />
             <el-table-column label="产品编码" align="center" prop="code" />
            <el-table-column label="产品图片" align="center" prop="imgUrl" >
              <template   slot-scope="scope">  
                <el-popover
                    placement="right"
                    title=""
                    trigger="hover"
                  >
                  <img slot="reference" :src="scope.row.imgUrl==null?defaultImg:(baseUrl+scope.row.imgUrl)" width="60"  >
                  <img :src="scope.row.imgUrl==null?defaultImg:(baseUrl+scope.row.imgUrl)" style="max-width: 300px;" >
                </el-popover>
              </template>     
            </el-table-column>
            <el-table-column label="产品名称" align="center" prop="name">
              <template slot-scope="scope">
                <el-link @click="openShow(scope.row)" :underline="false" type="primary" >{{scope.row.name}}</el-link>
              </template>
            </el-table-column>
           
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="价格" align="center" prop="price" width="120px">
                <template slot-scope="scope">
                  <span class="money">{{formatMoney(scope.row.price,',')}}</span>
                </template>
            </el-table-column>
              <el-table-column label="营销积分" align="center" prop="integral" width="120px">
                <template slot-scope="scope">
                   <span class="integral">{{formatMoney(scope.row.integral,',')}}</span>
                </template>
            </el-table-column>
              <el-table-column label="提成" align="center" prop="rate" width="120px">
                <template slot-scope="scope">
                   <span class="rate">{{formatMoney(scope.row.rate,',')}}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" >
              <template slot-scope="scope">
                    <el-tag prop="status" v-for="(item, index) in statusOptions"  :type="scope.row.status==1?'success':'danger'"  v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="所属分类" align="center" prop="cateName" />
            <el-table-column label="创建人" align="center" prop="nickName" />
            <el-table-column label="销售开始时间" align="center" prop="startTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="销售结束时间" align="center" prop="limitTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.limitTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column 
            fixed="right"
            width="120"
            label="操作" align="left" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['crm:product:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['crm:product:remove']"
                >删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
          
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
    </el-row>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-form  >
         <el-row>
            <el-col :span="24">
               <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                  <div class="el-upload__tip" slot="tip">
                    <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
                    <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                  </div>
                  <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload> 
            </el-col>
        </el-row>
        </el-form>
    
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="产品分类" prop="categoryId">
          <treeselect v-model="form.categoryId" :options="cateOptions" :show-count="true" placeholder="请选择产品分类" />
        </el-form-item>
        
        <el-form-item label="产品名称" prop="name" >
          <el-input v-model="form.name" maxlength="100" show-word-limit placeholder="请输入产品名称" />
        </el-form-item>
      
        <el-form-item label="产品编码" prop="code">
          <el-input v-model="form.code" maxlength="10" show-word-limit placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="主图" prop="imgUrl">
           <el-upload
              v-model="form.imgUrl"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
            <el-select
              v-model="form.unit"
              placeholder="请选择"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in unitOptions"
                :key="dict.dictLabel"
                :label="dict.dictLabel"
                :value="dict.dictLabel"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number" maxlength="10" show-word-limit v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="营销积分" prop="integral">
          <el-input type="number" maxlength="100" show-word-limit v-model="form.integral" placeholder="请输入营销积分" />
        </el-form-item>
        <el-form-item label="提成" prop="rate">
          <el-input type="number" maxlength="100" show-word-limit v-model="form.rate" placeholder="请输入提成" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="产品描述" prop="description">
            <editor ref="myeditor" :min-height="192" @on-text-change="updateText" />
        </el-form-item>
        <el-form-item label="销售开始时间" prop="startTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择销售开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售结束时间" prop="limitTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.limitTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择销售结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <el-drawer
     size="50%"
     :with-header="false"
      :title="show.title" :visible.sync="show.open"
      >
      <div class="app-container">
              <div class="product-info">
                <div class="product-info-title">
                    产品({{show.item.name}})
                </div>
                <table class="my-table">
                  <tr>
                    <td class="text-r">产品编号</td>
                    <td>{{show.item.code}} </td>
                    <td class="text-r">产品名称</td>
                    <td>{{show.item.name}} </td>
                  </tr>
                    <tr>
                    <td class="text-r">单位</td>
                    <td>{{show.item.unit}} </td>
                    <td class="text-r">价格</td>
                    <td>{{show.item.price}} </td>
                  </tr>
                  <tr>
                    <td class="text-r">营销积分</td>
                    <td>{{show.item.integral}} </td>
                    <td class="text-r">提成</td>
                      <td>{{show.item.rate}} </td>
                  </tr>
                   <tr>
                    <td class="text-r" >状态</td>
                    <td colspan="3">
                        <el-tag prop="status" v-for="(item, index) in statusOptions"  :type="show.item.status==1?'success':'danger'"  v-if="show.item.status==item.dictValue">{{item.dictLabel}}</el-tag>
                    </td>
                  </tr>
                    <tr>
                    <td class="text-r">所属分类</td>
                    <td>{{show.item.cateName}} </td>
                    <td class="text-r">创建人</td>
                    <td>{{show.item.nickName}} </td>
                  </tr>
                    <tr>
                    <td class="text-r">销售开始时间</td>
                    <td>{{show.item.startTime}} </td>
                    <td class="text-r">销售结束时间</td>
                    <td>{{show.item.limitTime}} </td>
                  </tr>
                     <!-- <tr>
                    <td class="text-r">描述</td>
                    <td colspan="3" v-html="show.item.description"> </td>
                    
                  </tr> -->
                 <!-- <img :src="show.item.imgUrl==null?defaultImg:(baseUrl+show.item.imgUrl)" width="60"  > -->
                </table>
                <div class="product-content" v-html="show.item.description">

                </div>
              </div>
        </div>
    </el-drawer>
  </div>
</template>

<script>
import { getAllProductCates } from "@/api/crm/productCategory";

import { listProduct, getProduct,importTemplate, delProduct, addProduct, updateProduct, exportProduct } from "@/api/crm/product";
import { treeselect } from "@/api/crm/productCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import defaultImg from '@/assets/image/default.png'
import Editor from '@/components/Editor/wang';
import { getToken } from "@/utils/auth";
export default {
  name: "Product",
  components: { Treeselect,Editor },
  data() {
    return {
        // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/crm/product/importData",
      },
      show:{
        title:"",
        open:false,
        item:{},
      },
      defaultImg:defaultImg,
      imageUrl: '',
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/upload",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        number: null,
        imgUrl: null,
        photos: null,
        unit: null,
        price: null,
        status: null,
        categoryId: null,
        description: null,
        createUserId: null,
        startTime: null,
        limitTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "产品分类不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "产品编号不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "价格不能为空", trigger: "blur" },
        ],
        integral: [
          { required: true, message: "营销积分不能为空", trigger: "blur" },
        ],
        rate: [
          { required: true, message: "提成不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        limitTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
        
      },
      // 树选项
      cateOptions: undefined,
      cateName: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      statusOptions:[],
      unitOptions:[],
      cateList:[],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("product_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("product_unit").then((response) => {
      this.unitOptions = response.data;
    });
    getAllProductCates().then((response) => {
        this.cateList = response.data;
    });
    
  },
  methods: {
    updateText(text){
      console.log(text);
        this.form.description=text
    },
    openShow(item){
      this.show.item=item;
      this.show.open=true;
      this.show.title="产品详情";
    },
     handleAvatarSuccess(res, file) {
        console.log(res);
        if(res.code==200){
          this.form.imgUrl=res.fileName;
          this.imageUrl = URL.createObjectURL(file.raw);
        }
        else{
          this.msgError(res.msg);
        }
        
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 jpeg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.cateOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id;
      this.getList();
    },
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        name: null,
        code: null,
        number: null,
        imgUrl: null,
        photos: null,
        unit: null,
        price: null,
        rate:0,
        integral:0,
        status: "0",
        categoryId: null,
        description: null,
        createUserId: null,
        createTime: null,
        updateTime: null,
        startTime: null,
        limitTime: null
      };
      
      this.imageUrl=null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品";
      setTimeout(() => {
        this.$refs.myeditor.initEditor();
      }, 200);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data;
        this.form.status =this.form.status.toString();
        if(response.data.imgUrl!=undefined||response.data.imgUrl!=null){
              this.imageUrl=this.baseUrl+response.data.imgUrl;
        }
        this.open = true;
        setTimeout(() => {

          this.$refs.myeditor.setText(this.form.description);
        }, 200);
        this.title = "修改产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addProduct(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$confirm('是否确认删除产品编号为"' + productIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProduct(productIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有产品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
        /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
     /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "产品导入";
      this.upload.open = true;
    },
     // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
<style scoped>

  .money{
      color: red;
  }
 
.product-info{
  margin:10px;
  overflow:auto;
}
 .my-table{
    margin: 10px 0px;
    width: 100%;
    text-align: left;
    border-collapse: collapse;
    border-spacing: 0;
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
}

.my-table td{
    width: 25%;
    word-break: break-all;
    word-wrap: break-word;
    border-right: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
    font: 500 14px Arial;
    padding: 10px 10px;
}
.my-table .text-r{
    color: #909399;
    text-align: right;
}
.product-content{
  width: 100%;
  overflow: hidden;
}
</style>
